package Dom4j;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class Dom4jDemo2 {

    @Test
    public void parseToList(){
        //1.创建Dom4j解析器对象，代表整个dom4j框架
        SAXReader saxReader = new SAXReader();
        //2.把XML文件加载到内存中成为一个Document文档对象
        //getResourceAsStream 直接去src下寻找文件
        Document document = null;
        try (  InputStream is=Dom4jDemo1.class.getResourceAsStream("/Contacts.xml")){
            document = saxReader.read(is);
            Element root=document.getRootElement();

            System.out.println(root.getName());
            List<Element> conElements = root.elements("contact");
            List<Contact> contacts=new ArrayList<>();
            for (Element conelement : conElements) {
                System.out.println(conelement.getName());
                Contact contact = new Contact();
                contact.setId(Integer.valueOf(conelement.attributeValue("id")));
                contact.setVip(Boolean.valueOf(conelement.attributeValue("vip")));
                contact.setName(conelement.elementTextTrim("name"));
                contact.setGendar((conelement.elementText("gender")).charAt(0));
                contact.setEmail(conelement.elementText("email"));
                contacts.add(contact);
            }
            //遍历list集合
            for (Contact contact : contacts) {
                System.out.println(contact);
            }

        } catch (DocumentException | IOException e) {
            e.printStackTrace();
        }

    }
}

